package com.hust360.percent.pojo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.hust360.percent.PercentApplication;
import com.hust360.percent.utils.StorageUtils;

import android.app.Application;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.util.Log;

public class DiscountInfoDAOImpl implements DiscountInfoDAO {

	PercentApplication application;

	public DiscountInfoDAOImpl(Application application) {
		this.application = (PercentApplication) application;
	}

	/**
	 * 通过主键来返回一个DiscountInfo, 如果未找到，返回null
	 */
	@Override
	public DiscountInfo findById(long discountId) {
		DiscountInfo info = null;
		SimpleDateFormat format = StorageUtils.simpleDateFormat;
		Cursor cursor = application.getLocalDB().query(DiscountInfo.TABLE_NAME,
				DiscountInfo.COLUMNS,
				DiscountInfo.DISCOUNT_INFO_ID_COLUMN + "=" + discountId, null,
				null, null, null);
		if (cursor.moveToFirst()) {
			info = new DiscountInfo();
			info.setDiscountImage(Arrays.asList(cursor.getString(
					cursor.getColumnIndex(DiscountInfo.DISCOUNT_IMAGE_COLUMN))
					.split("<::>")));
			info.setDiscountInfo(cursor.getString(cursor
					.getColumnIndex(DiscountInfo.DISCOUNT_INFO_COLUMN)));
			info.setDiscountInfoId(cursor.getLong(cursor
					.getColumnIndex(DiscountInfo.DISCOUNT_INFO_ID_COLUMN)));
			info.setDiscountType(cursor.getInt(cursor
					.getColumnIndex(DiscountInfo.DISCOUNT_TYPE_COLUMN)));
			info.setLiked(cursor.getLong(cursor
					.getColumnIndex(DiscountInfo.LIKED_COLUMN)));
			info.setShopId(cursor.getLong(cursor
					.getColumnIndex(DiscountInfo.SHOP_ID_COLUMN)));
			info.setDiscount(cursor.getInt(cursor
					.getColumnIndex(DiscountInfo.DISCOUNT_COLUMN)));
			info.setType(cursor.getInt(cursor
					.getColumnIndex(DiscountInfo.TYPE_COLUMN)));
			info.setAreaId(cursor.getLong(cursor
					.getColumnIndex(DiscountInfo.AREA_ID_COLUMN)));
			try {
				info.setBeginDate(format.parse(cursor.getString(cursor
						.getColumnIndex(DiscountInfo.BEGIN_DATE_COLUMN))));
				info.setEndDate(format.parse(cursor.getString(cursor
						.getColumnIndex(DiscountInfo.END_DATE_COLUMN))));
				info.setCreateDate(format.parse(cursor.getString(cursor
						.getColumnIndex(DiscountInfo.CREATE_DATE_COLUMN))));
			} catch (ParseException e) {
				e.printStackTrace();
			}

		}
		cursor.close();
		return info;
	}

	/**
	 * 通过一个实例来返回类似的记录， 返回值总不会是null
	 */
	@Override @Deprecated
	public List<DiscountInfo> findByExample(DiscountInfo example) {
		SimpleDateFormat format = StorageUtils.simpleDateFormat;
		/*
		 * 将对象的属性合并成一个sql语句的块
		 */
		String info = example.getDiscountInfo() == null ? ""
				: DiscountInfo.DISCOUNT_INFO_COLUMN + "=" + "'"
						+ example.getDiscountInfo() + "'";
		String discountType = example.getDiscountType() == null ? ""
				: DiscountInfo.DISCOUNT_TYPE_COLUMN + "=" + "'"
						+ example.getDiscountType() + "'";
		String info_id = example.getDiscountInfoId() == null ? ""
				: DiscountInfo.DISCOUNT_INFO_ID_COLUMN + "=" + "'"
						+ example.getDiscountInfoId() + "'";
		String shop_id = example.getShopId() == null ? ""
				: DiscountInfo.SHOP_ID_COLUMN + "=" + "'" + example.getShopId()
						+ "'";
		String liked = example.getLiked() == null ? ""
				: DiscountInfo.LIKED_COLUMN + "=" + "'" + example.getLiked()
						+ "'";
		List<String> list = example.getDiscountImage();
		String imagePaths = "";
		if (list != null && list.size() != 0) {
			String s;
			for (int i = 0; i < list.size(); i++) {
				s = list.get(i);
				imagePaths += s + "<::>";
			}
			imagePaths += list.get(list.size() - 1);
		}
		String discount = example.getDiscountInfo() == null ? ""
				: DiscountInfo.DISCOUNT_COLUMN + "=" + "'"
						+ example.getDiscount() + "'";

		String type = example.getType() == null ? "" : DiscountInfo.TYPE_COLUMN
				+ "=" + "'" + example.getType() + "'";
		String areaId = example.getAreaId() == null ? ""
				: DiscountInfo.AREA_ID_COLUMN + "=" + "'" + example.getAreaId()
						+ "'";
		String beginDate = example.getBeginDate() == null ? ""
				: DiscountInfo.BEGIN_DATE_COLUMN + "=" + "'"
						+ format.format(example.getBeginDate()) + "'";
		String endDate = example.getEndDate() == null ? ""
				: DiscountInfo.END_DATE_COLUMN + "=" + "'"
						+ format.format(example.getEndDate()) + "'";
		String createDate = example.getEndDate() == null ? ""
				: DiscountInfo.CREATE_DATE_COLUMN + "=" + "'"
						+ format.format(example.getCreateDate()) + "'";

		String selection = info;
		selection += info.equals("") || discountType.equals("") ? discountType
				: " AND " + discountType;
		selection += discountType.equals("") || info_id.equals("") ? info_id
				: " AND " + info_id;
		selection += info_id.equals("") || shop_id.equals("") ? shop_id
				: " AND " + shop_id;
		selection += shop_id.equals("") || liked.equals("") ? liked : " AND "
				+ liked;
		selection += liked.equals("") || imagePaths.equals("") ? imagePaths
				: " AND " + imagePaths;
		selection += imagePaths.equals("") || discount.equals("") ? discount
				: " AND " + discount;
		selection += discount.equals("") || type.equals("") ? type : " AND "
				+ type;
		selection += type.equals("") || areaId.equals("") ? areaId : " AND "
				+ areaId;
		selection += areaId.equals("") || beginDate.equals("") ? beginDate
				: " AND " + beginDate;
		selection += beginDate.equals("") || endDate.equals("") ? endDate
				: " AND " + endDate;
		selection += endDate.equals("") || createDate.equals("") ? createDate
				: " AND " + createDate;

		// 执行查询语句
		Cursor cursor = application.getLocalDB().query(DiscountInfo.TABLE_NAME,
				null, selection, null, null, null, null);

		/*
		 * 将查询到的数据生成对象集合，并返回
		 */
		List<DiscountInfo> infoList = new ArrayList<DiscountInfo>(
				cursor.getCount());
		DiscountInfo discountInfo;
		while (cursor.moveToNext()) {
			discountInfo = new DiscountInfo();
			discountInfo.setDiscountImage(Arrays.asList(cursor.getString(
					cursor.getColumnIndex(DiscountInfo.DISCOUNT_IMAGE_COLUMN))
					.split("<::>")));
			discountInfo.setDiscountInfo(cursor.getString(cursor
					.getColumnIndex(DiscountInfo.DISCOUNT_INFO_COLUMN)));
			discountInfo.setDiscountInfoId(cursor.getLong(cursor
					.getColumnIndex(DiscountInfo.DISCOUNT_INFO_ID_COLUMN)));
			discountInfo.setDiscountType(cursor.getInt(cursor
					.getColumnIndex(DiscountInfo.DISCOUNT_TYPE_COLUMN)));
			discountInfo.setLiked(cursor.getLong(cursor
					.getColumnIndex(DiscountInfo.LIKED_COLUMN)));
			discountInfo.setShopId(cursor.getLong(cursor
					.getColumnIndex(DiscountInfo.SHOP_ID_COLUMN)));
			discountInfo.setDiscount(cursor.getInt(cursor
					.getColumnIndex(DiscountInfo.DISCOUNT_COLUMN)));
			discountInfo.setType(cursor.getInt(cursor
					.getColumnIndex(DiscountInfo.TYPE_COLUMN)));
			discountInfo.setAreaId(cursor.getLong(cursor
					.getColumnIndex(DiscountInfo.AREA_ID_COLUMN)));
			try {
				discountInfo.setBeginDate(format.parse(cursor.getString(cursor
						.getColumnIndex(DiscountInfo.BEGIN_DATE_COLUMN))));
				discountInfo.setEndDate(format.parse(cursor.getString(cursor
						.getColumnIndex(DiscountInfo.END_DATE_COLUMN))));
				discountInfo.setCreateDate(format.parse(cursor.getString(cursor
						.getColumnIndex(DiscountInfo.CREATE_DATE_COLUMN))));
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (NullPointerException e) {
				discountInfo.setBeginDate(new Date());
			}

			// 计算距离
			if (application.isHasPoc()) {
				float[] results = new float[2];
				Shop shop = application.getShopDao().findById(
						discountInfo.getShopId());
				if (shop != null) {
					Location.distanceBetween(application.getLatitude(),
							application.getLongitude(), shop.getLatitude(),
							shop.getLongitude(), results);
					Log.e("Distance", results[0] + "");
					discountInfo.setDistance(results[0]);
				}
			}
			infoList.add(discountInfo);
		}
		cursor.close();
		return infoList;
	}

	/**
	 * 将info对象保存到数据库中
	 */
	@Override
	public void save(DiscountInfo info) {

		ContentValues values = new ContentValues();
		values.put(DiscountInfo.DISCOUNT_INFO_COLUMN, info.getDiscountInfo());
		values.put(DiscountInfo.DISCOUNT_INFO_ID_COLUMN,
				info.getDiscountInfoId());
		values.put(DiscountInfo.DISCOUNT_TYPE_COLUMN, info.getDiscountType());
		values.put(DiscountInfo.DISCOUNT_COLUMN, info.getDiscount());
		values.put(DiscountInfo.LIKED_COLUMN, info.getLiked());
		values.put(DiscountInfo.SHOP_ID_COLUMN, info.getShopId());
		values.put(
				DiscountInfo.BEGIN_DATE_COLUMN,
				info.getBeginDate() == null ? null
						: StorageUtils.simpleDateFormat.format(info
								.getBeginDate()));
		values.put(
				DiscountInfo.END_DATE_COLUMN,
				info.getEndDate() == null ? null
						: StorageUtils.simpleDateFormat.format(info
								.getEndDate()));
		values.put(
				DiscountInfo.CREATE_DATE_COLUMN,
				info.getCreateDate() == null ? null
						: StorageUtils.simpleDateFormat.format(info
								.getCreateDate()));
		values.put(DiscountInfo.AREA_ID_COLUMN, info.getAreaId());
		values.put(DiscountInfo.TYPE_COLUMN, info.getType());

		List<String> list = info.getDiscountImage();
		String imagePaths = "";
		if (list != null && list.size() != 0) {
			String s = "";
			for (int i = 0; i < list.size() - 1; i++) {
				s = list.get(i);
				imagePaths += s + "<::>";
			}
			s += list.get(list.size() - 1);
		}
		values.put(DiscountInfo.DISCOUNT_IMAGE_COLUMN, imagePaths);
		application.getLocalDB().insertWithOnConflict(DiscountInfo.TABLE_NAME,
				null, values, SQLiteDatabase.CONFLICT_REPLACE);
	}

	@Override
	public List<DiscountInfo> findByArgs(String[] columns, String selection,
			String[] selectionArgs, String groupBy, String having,
			String orderBy) {

		SimpleDateFormat format = StorageUtils.simpleDateFormat;

		ArrayList<DiscountInfo> list = null;
		Cursor c = application.getLocalDB().query(DiscountInfo.TABLE_NAME,
				columns, selection, selectionArgs, groupBy, having, orderBy);
		list = new ArrayList<DiscountInfo>(c.getCount());
		DiscountInfo discountInfo;
		while (c.moveToNext()) {
			discountInfo = new DiscountInfo();
			discountInfo.setDiscountImage(Arrays.asList(c.getString(
					c.getColumnIndex(DiscountInfo.DISCOUNT_IMAGE_COLUMN))
					.split("<::>")));
			discountInfo.setDiscountInfo(c.getString(c
					.getColumnIndex(DiscountInfo.DISCOUNT_INFO_COLUMN)));
			discountInfo.setDiscountInfoId(c.getLong(c
					.getColumnIndex(DiscountInfo.DISCOUNT_INFO_ID_COLUMN)));
			discountInfo.setDiscountType(c.getInt(c
					.getColumnIndex(DiscountInfo.DISCOUNT_TYPE_COLUMN)));
			discountInfo.setLiked(c.getLong(c
					.getColumnIndex(DiscountInfo.LIKED_COLUMN)));
			discountInfo.setShopId(c.getLong(c
					.getColumnIndex(DiscountInfo.SHOP_ID_COLUMN)));
			discountInfo.setDiscount(c.getInt(c
					.getColumnIndex(DiscountInfo.DISCOUNT_COLUMN)));
			discountInfo.setType(c.getInt(c
					.getColumnIndex(DiscountInfo.TYPE_COLUMN)));
			discountInfo.setAreaId(c.getLong(c
					.getColumnIndex(DiscountInfo.AREA_ID_COLUMN)));
			try {
				discountInfo.setBeginDate(format.parse(c.getString(c
						.getColumnIndex(DiscountInfo.BEGIN_DATE_COLUMN))));
			} catch (Exception e) {
				e.printStackTrace();
				discountInfo.setBeginDate(new Date());
			}
			try {
				discountInfo.setEndDate(format.parse(c.getString(c
						.getColumnIndex(DiscountInfo.END_DATE_COLUMN))));

			} catch (Exception e) {
				e.printStackTrace();
				discountInfo.setEndDate(new Date());
			}
			try {
				discountInfo.setCreateDate(format.parse(c.getString(c
						.getColumnIndex(DiscountInfo.CREATE_DATE_COLUMN))));
			} catch (Exception e) {
				e.printStackTrace();
				discountInfo.setCreateDate(new Date());
			}

			// 计算距离
			if (application.isHasPoc()) {
				float[] results = new float[2];
				Shop shop = application.getShopDao().findById(
						discountInfo.getShopId());
				if (shop != null) {
					Location.distanceBetween(application.getLatitude(),
							application.getLongitude(), shop.getLatitude(),
							shop.getLongitude(), results);
					Log.e("Distance", results[0] + "");
					discountInfo.setDistance(results[0]);
				}
			}
			list.add(discountInfo);
		}
		c.close();
		return list;
	}

}
